/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package android.reasons;

import android.app.Activity;
import static android.app.Activity.RESULT_OK;
import android.app.ContextoAndroid;
import android.app.FontManager;
import android.app.Mensaje;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.entidades.Usuario;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import static android.reasons.Inicio.RESULT_LOAD_IMAGE;
import android.view.View;
import android.web.service.WebService;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import java.io.File;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

/**
 *
 * @author efraingutierrez
 */
public class EditarPerfil extends Activity implements View.OnClickListener 
{
    private Button btnChoose;
    private ImageButton accept;
    private ImageView imgDisplay;
    private LinearLayout abs;
    private EditText etID,etPassword,etNombre;
    private String UploadImagePath,UploadImageName;
    private ProgressDialog dialog;
    private Boolean imgFlag = false;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ContextoAndroid.context = this;
        this.setContentView(R.layout.editarperfil);
        
        abs = (LinearLayout)this.findViewById(R.id.linearEditar);
        abs.setBackgroundResource(R.drawable.turquesa);
        accept = (ImageButton)this.findViewById(R.id.btnOkSignInEditar);
        imgDisplay = (ImageView)this.findViewById(R.id.imgViewEditar);
        btnChoose = (Button)this.findViewById(R.id.btnFotoEditar);
        btnChoose.setOnClickListener(this);
        etID = (EditText)this.findViewById(R.id.etIDSignInEditar);
        etPassword = (EditText)this.findViewById(R.id.etPassEditar);
        etNombre = (EditText)this.findViewById(R.id.etNombreEditar);
        accept.setOnClickListener(this);
        FontManager.changeFont(abs);
        fill();
    }
    
    private void fill()
    {
        this.etID.setText(ContextoAndroid.usuario.correo);
        this.etNombre.setText(ContextoAndroid.usuario.nombre);
        this.etPassword.setText(ContextoAndroid.usuario.password);
        this.etID.setText(ContextoAndroid.usuario.correo);
        Usuario.changeImage(imgDisplay);
        this.etID.setEnabled(false);
    }
    
    public void onClick(View arg0) 
    {
        
        if(arg0.getId() == R.id.btnFotoEditar)
        {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            this.startActivityForResult(i, Inicio.RESULT_LOAD_IMAGE);
        }
        else if(arg0.getId() == R.id.btnOkSignInEditar)
        {
            final String nickStr = etID.getText().toString();
            final String passStr = etPassword.getText().toString();
            final String nombre = etNombre.getText().toString();

            if(ContextoAndroid.usuario.tipo !=1)
            {
            
                if(!nickStr.equals("") && !passStr.toString().equals("") && !nombre.equals(""))
                {
                    
                    if(WebService.conexionInternert())
                    {
                        new WebPetition().execute(UploadImagePath,UploadImageName,nickStr,passStr,nombre);
                    }
                    else Mensaje.Mostrar("Error: No Existe Conexion a Internet");
                }
                else Mensaje.Mostrar("Error: Datos Incompletos");
            }
            else Mensaje.Mostrar("Error: Ha Ingresado con los Datos de Facebook... No Se Pueden Editar");
        }
       
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) 
        {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = this.getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            UploadImagePath = cursor.getString(columnIndex);
            cursor.close();
            File imgFile = new  File(UploadImagePath);
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            imgDisplay.setImageBitmap(myBitmap);
            UploadImageName = imgFile.getName();
            imgFlag = true;
            // String picturePath contains the path of selected Image
        }
    }
    
    public void save(String name)
    {
          
    }
    private class WebPetition extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(ContextoAndroid.context);
            dialog.setIndeterminate(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setCancelable(true);
            dialog.setMessage("Guardando...");
            dialog.show();
        }
        @Override
        protected Boolean doInBackground(String... params) 
        {
            String correo = params[2];
            String pass = params[3];
            String nombre = params[4];
            String foto = imgFlag ? params[1] : ContextoAndroid.usuario.foto;
            int tipo = ContextoAndroid.usuario.tipo;
            Boolean b = true;
            if(imgFlag)
                b = android.web.service.Photo.uploadPhoto(params[0]);
            ArrayList<NameValuePair> lst = new ArrayList<NameValuePair>();
            lst.add(new BasicNameValuePair("id",correo));
            lst.add(new BasicNameValuePair("password",pass));
            lst.add(new BasicNameValuePair("foto",foto));
            lst.add(new BasicNameValuePair("nombre",nombre));
            JSONArray array = WebService.getJSONArray(lst, "Alta", "Controladores/editUsuario.php");
            try {
                String str = array.getString(0);
                if(!str.equals("1"))
                    return false;
            } catch (Exception ex) {
                return false;
            }
            if(b)
            {
                
                Usuario u = new Usuario(correo,pass,nombre,foto,tipo);
                ContextoAndroid.usuario = u;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) 
        {
            dialog.dismiss();
            if(result)
            {
                Mensaje.Mostrar("Se Ha Actualizado el Perfil");
            }
            else Mensaje.Mostrar("Error...");
        }
        @Override
        protected void onProgressUpdate(Integer... values) 
        {
            dialog.setMessage("Guardando...");
            dialog.setProgress(values[0]);
        }
    }
}